// mqtt_control.c
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "hi_io.h"
#include "hi_time.h"
#include "hi_timer.h"

#include "robot_control.h"
#include "mqtt_test.h"

// GPIO定义（与trace_model保持一致）
#define GPIO0 0
#define GPIO1 1
#define GPIO9 9
#define GPIO10 10
#define GPIO_FUNC 0

// 控制状态
int g_last_mqtt_command = 0;
int g_last_mqtt_speed=0;
// mqtt_test.c中传来的变量
extern unsigned char g_car_status;
//l9110s.c中传来的函数，用于控制车辆状态
extern void gpio_control(unsigned int gpio, IotGpioValue value);
extern void car_forward(void);
extern void car_backward(void);
extern void car_left(void);
extern void car_right(void);
extern void car_stop(void);
//l9110s.c中传来的函数用于控制pwm速度
extern void control_speed(int num);

//MQTT命令处理定时器回调 
void mqtt_timer_callback(unsigned int arg)
{
    int current_command = get_mqtt_command();//看下最新接收到的消息是否符合
    int current_speed = get_mqtt_speed();//看下最新接收到的消息是否符合
    // 只在命令发生变化时处理
    if (current_command != g_last_mqtt_command) {
        printf("MQTT command changed from %d to %d\n", g_last_mqtt_command, current_command);   
        g_last_mqtt_command = current_command;
    }
    if (current_speed != g_last_mqtt_speed) {
        printf("speed changed from %d to %d\n", g_last_mqtt_speed, current_speed);   
        g_last_mqtt_speed = current_speed;
    }
}

// MQTT控制模块主函数
void mqtt_control_module(void)
{
    unsigned int timer_id2;
    hi_timer_create(&timer_id2);
    
    // 启动定时器，每10ms检查一次MQTT命令，监听是否发生了变化

    hi_timer_start(timer_id2, HI_TIMER_TYPE_PERIOD, 10, mqtt_timer_callback, 0);
    
    // 默认状态是停止
    car_stop();
    
    printf("MQTT control module started\n");
    
    while (1) {
         control_speed(g_last_mqtt_speed);
         switch (g_last_mqtt_command) {
            case 1: // 前进
                car_forward();
                printf("MQTT: Moving forward\n");
                break;
            case 2: // 后退
                car_backward();
                printf("MQTT: Moving backward\n");
                break;
            case 3: // 左转
                car_left();
                printf("MQTT: Turning left\n");
                break;
            case 4: // 右转
                car_right();
                printf("MQTT: Turning right\n");
                break;
            case 5: // 停止
                car_stop();
                printf("MQTT: Stopping\n");
                break;
            default: // 保持当前状态
                break;
        }

        hi_udelay(20);  // 20微秒延迟
        
        // 检查是否需要退出MQTT控制模式
        if (g_car_status != CAR_MQTT_CONTROL_STATUS) {
            break;
        }
    }
    
    // 停止车辆并清理定时器
    car_stop();
    hi_timer_delete(timer_id2);
    
    printf("MQTT control module stopped\n");
}